package com.android.gtravelling;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.android.dto.PlacesDTO;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class PlaceList extends Activity {

	
	private ListView mainListView;
	private ArrayList<PlacesDTO> listPlaces;
	private ArrayAdapter<PlacesDTO> listAdapter;
	private WebserviceCaller webCaller;
	private EditText filterText = null;
	ConvertUnsigned conChar=new ConvertUnsigned();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_province);
		
		mainListView = (ListView) findViewById(R.id.lv_province);

		webCaller = new WebserviceCaller();
		listPlaces = webCaller.selectAllPlaces();
		// ArrayList<ProvincesDTO> sm=listProvinces.
		listAdapter = new PlacesDTOArrayAdapter(this, listPlaces);
		mainListView.setAdapter(listAdapter);
		mainListView.setTextFilterEnabled(true);
		filterText = (EditText) findViewById(R.id.edt_search);
		filterText.addTextChangedListener(filterTextWatcher);
		mainListView.setFastScrollEnabled(true);

		mainListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> a, View v, int i, long l) {
				try {
					// int poss = mainListView.getse.getSelectedItemPosition();
					int id = listPlaces.get(i).getId();
					Intent is = new Intent(v.getContext(), PlaceDetail.class);
					is.putExtra(Intent.EXTRA_TEXT, String.valueOf(id));
					startActivity(is);
				} catch (Exception e) {
					System.out.println("Nay, cannot get the selected index");
				}
			}
		});
		
	}
	
	private TextWatcher filterTextWatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			
				listAdapter.getFilter().filter(filterText.getText().toString());
			listAdapter.notifyDataSetChanged();
		}

	};
	
	private class PlacesDTOViewHolder {
		private ImageView imgView;

		public ImageView getImgView() {
			return imgView;
		}

		public void setImgView(ImageView imgView) {
			this.imgView = imgView;
		}

		private TextView textView;
		private TextView textView1;

		public PlacesDTOViewHolder(ImageView imgView, TextView textView,
				TextView textView1) {
			this.imgView = imgView;
			this.textView = textView;
			this.textView1 = textView1;
		}

		public TextView getTextView() {
			return textView;
		}

		public TextView getTextView1() {
			return this.textView1;
		}

		public void setTextView(TextView textView) {
			this.textView = textView;
		}
	}

	private class PlacesDTOArrayAdapter extends ArrayAdapter<PlacesDTO> implements Filterable{

		private LayoutInflater inflater;

		public ArrayList<PlacesDTO> lstAllItem;
		public ArrayList<PlacesDTO> lstSubItem;
		private PTypeFilter filter;
		
		public PlacesDTOArrayAdapter(Context context,
				ArrayList<PlacesDTO> planetList) {
			super(context, R.layout.row_province, R.id.tv_province_title,
					planetList);
			this.lstSubItem=planetList;
			lstAllItem=planetList;
			inflater = LayoutInflater.from(context);

		}

		@Override
	    public int getCount() {
	        return lstSubItem.size();
	    }
		@Override
		public Filter getFilter() {
		    if (filter == null){
		      filter  = new PTypeFilter();
		    }
		    return filter;
		  }
		
		private InputStream fetch(String urlString)
				throws MalformedURLException, IOException {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet request = new HttpGet(urlString);
			HttpResponse response = httpClient.execute(request);
			return response.getEntity().getContent();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			PlacesDTO place = lstSubItem.get(position);

			// The child views in each row.
			ImageView imgView;
			TextView textView;
			TextView textView1;
			// Create a new row view
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.row_province, null);
				// Find the child views.
				imgView = (ImageView) convertView
						.findViewById(R.id.imgRowContent);
				textView = (TextView) convertView
						.findViewById(R.id.tv_province_title);

				textView1 = (TextView) convertView
						.findViewById(R.id.tv_province_Descrip);

				// Optimization: Tag the row with it's child views, so we don't
				// have to
				// call findViewById() later when we reuse the row.
				convertView.setTag(new PlacesDTOViewHolder(imgView,
						textView, textView1));
			}
			// Reuse existing row view
			else {
				// Because we use a ViewHolder, we avoid having to call
				// findViewById().
				PlacesDTOViewHolder viewHolder = (PlacesDTOViewHolder) convertView
						.getTag();
				imgView = viewHolder.getImgView();
				textView = viewHolder.getTextView();
				textView1 = viewHolder.getTextView1();
			}

			/*String imgURL = prov.getImgURL();
			if (imgURL == null) {*/
				imgView.setImageResource(R.drawable.cui_bap);
			/*} else {
				InputStream is = null;
				try {
					is = fetch(imgURL);//"http://dl.dropbox.com/u/24886653/hinhchoandroid/W128X160PNT065.jpg");
				} catch (Exception e) {

				}

				Drawable drawable = Drawable.createFromStream(is, "src");

				// Display planet data

				imgView.setImageDrawable(drawable);
			}*/
			textView.setText(place.getName());
			textView1.setText(place.getAddress()//.getDescription()
					);

			return convertView;
		}

		private class PTypeFilter extends Filter{

		    @SuppressWarnings("unchecked")
		    @Override
		    protected void publishResults(CharSequence prefix,
		                                  FilterResults results) {
		      // NOTE: this function is *always* called from the UI thread.
		       lstSubItem =  (ArrayList<PlacesDTO>)results.values;

		        notifyDataSetChanged();
		    }

		    @SuppressWarnings("unchecked")
		    protected FilterResults performFiltering(CharSequence prefix) {
		          // NOTE: this function is *always* called from a background thread, and
		          // not the UI thread. 

		          FilterResults results = new FilterResults();
		          ArrayList<PlacesDTO> i = new ArrayList<PlacesDTO>();

		          if (prefix!= null && prefix.toString().length() > 0) {

		              for (int index = 0; index < lstAllItem.size(); index++) {
		            	  PlacesDTO si = lstAllItem.get(index);
		            	  
		                 // if(si.getName().toLowerCase().contains(prefix.toString().toLowerCase()) == true){
		            	  if((conChar.ConvertString(si.getName()).contains(prefix.toString().toLowerCase()) == true)||
		            			  (conChar.ConvertString(si.getAddress()).contains(prefix.toString().toLowerCase()) == true) ){
		                    i.add(si); 
		                  }
		              }
		              results.values = i;
		              results.count = i.size();                   
		          }
		          else{
		              synchronized (lstAllItem){
		                  results.values = lstAllItem;
		                  results.count = lstAllItem.size();
		              }
		          }

		          return results;
		    }
		}
		
	}
}
